//
//  ADUserAcountViewModel.swift
//  myBlog
//
//  Created by mac2014 on 16/3/24.
//  Copyright © 2016年 AD. All rights reserved.
//

import UIKit

class ADUserAcountViewModel: NSObject {
    
    ///mark - 属性
    
    //单例
    static let sharedInstance: ADUserAcountViewModel = ADUserAcountViewModel()
    
    //用户账号
    var userAccount: ADUserAcount?
    
    //判断是否登录：登录账号不为空则判断为登录状态
    var isLogin: Bool {
        get {
            return userAccount != nil
        }
    }
    
    //归档路径
    let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/userAcount.plist")
    
    
    ///mark - 系统方法
    override init() {
        super.init()
        
        //从沙盒中加载用户账号信息
        userAccount = loadUserAccount()
    }
    

    
    ///mark - 自定义方法
    //加载acess_token
    func loadAccessToken(code: String, completion: (error: NSError?) -> ()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
//        //发送post请求
        ADNetWorkingTool.sharedInstance.POST(urlString, parameters: parameters, progress: nil) {
            (result, error) -> () in
            if error != nil {
                completion(error: error)
                return
            }
            //将网络返回的信息赋给属性保存，外界访问的时候直接通过属性加载
            self.userAccount = ADUserAcount(dict: result!)
            //将账号信息保存到沙盒
            self.saveUserAcount()
            
            completion(error: nil)
            }
        }
    
    //将access_token保存到沙盒
    func saveUserAcount() {
        if userAccount != nil {
            //如果有账号信息，归档保存
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: path)
        }
    }
    
    //从沙盒中加载数据
    func loadUserAccount() -> ADUserAcount?{
        //从沙盒中解档出userAcount数据
        let userAcount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ADUserAcount
        
        //如果userAcount不为空，并且未过期，则返回用户数据
        if userAcount != nil && userAcount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            return userAcount
        }
        return nil
    }
    
    //加载用户信息
    func loadUserInfo(completion: (error: NSError?) -> ()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters: [String: AnyObject] = [
            "access_token": userAccount!.access_token!,
            "uid": userAccount!.uid!
        ]
        ADNetWorkingTool.sharedInstance.GET(urlString, parameters: parameters, progress: nil) { (result, error) -> () in
            if error != nil {
                completion(error: error)
                return
            }
            self.userAccount?.screen_name = result?["screen_name"] as? String
            self.userAccount?.avatar_large = result?["avatar_large"] as? String
            
            self.saveUserAcount()
            
            completion(error: nil)
            
        }
    } 
}
    

    


